package com.ask.service.businessService.impl;

import cn.hutool.core.bean.BeanUtil;
import com.ask.dto.Result;
import com.ask.dto.UserDTO;
import com.ask.entity.Follow;
import com.ask.mapper.FollowMapper;
import com.ask.service.businessService.IFollowService;
import com.ask.service.businessService.IUserService;
import com.ask.threadlocals.UserHolder;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class FollowServiceImpl extends ServiceImpl<FollowMapper, Follow> implements IFollowService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private IUserService userService;

    /**
     * 关注 or 取关
     *
     * @param followUserId
     * @param isFollow
     * @return
     */
    @Override
    public Result follow(Long followUserId, Boolean isFollow) {
        Long userId = UserHolder.getUser().getId();
        String key = "follows:" + userId;
        if (isFollow) { // 关注
            // 数据库新增
            Follow follow = new Follow();
            follow.setUserId(userId);
            follow.setFollowUserId(followUserId);
            boolean isSuccess = save(follow);
            // redis新增
            if (isSuccess)
                stringRedisTemplate.opsForSet().add(key, followUserId.toString());
        } else { // 取关
            // 数据库删除
            boolean isSuccess = remove(new QueryWrapper<Follow>()
                    .eq("user_id", userId)
                    .eq("follow_user_id", followUserId));
            // redis删除
            if (isSuccess)
                stringRedisTemplate.opsForSet().remove(key, followUserId.toString());
        }
        return Result.success();
    }

    /**
     * 判断当前用户是否关注
     *
     * @param followUserId
     * @return
     */
    @Override
    public Result isFollow(Long followUserId) {
        Long userId = UserHolder.getUser().getId();
        Long count = query()
                .eq("user_id", userId).eq("follow_user_id", followUserId)
                .count();
        return Result.success(count > 0);
    }

    /**
     * 查询共同关注
     *
     * @param id
     * @return
     */
    @Override
    public Result followCommons(Long id) {
        // 查询共同关注的用户id
        Long userId = UserHolder.getUser().getId();
        String k1 = "follows:" + userId;
        String k2 = "follows:" + id;
        Set<String> intersect = stringRedisTemplate.opsForSet().intersect(k1, k2);
        // 无交集
        if (intersect == null || intersect.isEmpty())
            return Result.success(Collections.emptyList());
        // 查询交集关注的用户信息
        List<Long> ids = intersect.stream().map(Long::valueOf).collect(Collectors.toList());
        List<UserDTO> dtoList = userService.listByIds(ids)
                .stream()
                .map(user -> BeanUtil.copyProperties(user, UserDTO.class))
                .collect(Collectors.toList());
        return Result.success(dtoList);
    }
}
